import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 分组捕获
 * 日期 2022/5/5 10:25
 * 创建者：john driver
 */
public class Group {
    public static void main(String[] args) {
        // 费命名
        Pattern pattern = Pattern.compile("abc(ef)(g(h))");
        Matcher matcher = pattern.matcher("abcefgh");
        while (matcher.find()){
            System.out.println(matcher.group(0));
            System.out.println(matcher.group(1));
            System.out.println(matcher.group(2));
            System.out.println(matcher.group(3));
        }
         // 命名分组
        pattern = Pattern.compile("abc(?<g1>ef)(?<g2>g(?<g3>h))");
        matcher = pattern.matcher("abcefgh");
        while (matcher.find()){
            System.out.println(matcher.group(0));
            System.out.println(matcher.group("g1"));
            System.out.println(matcher.group("g2"));
            System.out.println(matcher.group("g3"));
        }
        //非捕获
        pattern = Pattern.compile("abc(?:ef|gh)");
        matcher = pattern.matcher("abcefgh");
        while (matcher.find()){
            System.out.println("?:\t"+matcher.group(0));
        }

        pattern = Pattern.compile("abc(?=ef|gh)");
        matcher = pattern.matcher("abcefgh");
        while (matcher.find()){
            System.out.println("?=\t"+matcher.group(0));
        }

        pattern = Pattern.compile("abc(?!ef|gh)");
        matcher = pattern.matcher("abcdefgh");
        while (matcher.find()){
            System.out.println("?!\t"+matcher.group(0));
        }
        //反向引用
        pattern = Pattern.compile("(\\w{2})\\1{2}(cd)");
        matcher = pattern.matcher("abababcdefgh");
        while (matcher.find()){
            System.out.println(matcher.group(0));
            System.out.println(matcher.group(1));
            System.out.println(matcher.group(2));
        }
        System.out.println(matcher.replaceAll("$2"));
        String s = Pattern.compile("(\\w{2})\\1{2}(cd)").matcher("abababcdefgh").replaceAll("$2");
        String s2 = "abababcdefgh".replaceAll("(\\w{2})\\1{2}(cd)", "$2");
        System.out.println(s2);

    }
}
